<script setup>
import MenuTreeSelect from "../../../components/menu-tree-select.vue";
import {importBatch} from "../../../apis/sys/menu.js";
import {useMessage} from "naive-ui";

const showModel = defineModel('show')
const emits = defineEmits(['success'])

const formRef = ref(undefined)
const initFormDataValue = {
  parentId: undefined,
  script: undefined
}
const formData = ref({
  ...initFormDataValue
})

const message = useMessage()

const onFinish = () => {
  formRef.value.validate()
      .then(async () => {
        const scriptData = {
          ...JSON.parse(formData.value.script),
          parentId: formData.value.parentId
        }
        const {code} = await importBatch(scriptData)
        if (code === 0) {
          message.success('导入成功')
          showModel.value = false
          emits('success')
        }
      })
}
const onAfterLeave = () => {
  resetForm()
}
const resetForm = () => {
  formData.value = {...initFormDataValue}
}

const rules = {
  parentId: [
    {required: true, message: '请选择上级菜单', trigger: 'change'}
  ],
  script: [
    {required: true, message: '请输入脚本', trigger: 'blur'}
  ]
}
</script>

<template>
  <n-drawer v-model:show="showModel"
            resizable
            :min-width="502"
            :default-width="502"
            @after-leave="onAfterLeave">
    <n-drawer-content title="导入">
      <n-form
          :rules="rules"
          :model="formData"
          ref="formRef"
          label-placement="left"
          label-width="80">
        <n-form-item label="上级菜单" path="parentId">
          <menu-tree-select v-model:value="formData.parentId"/>
        </n-form-item>
        <n-form-item label="导入脚本" path="script">
          <n-input
              v-model:value="formData.script"
              type="textarea"
              placeholder="请输入"
              :autosize="{minRows: 10}"/>
        </n-form-item>
      </n-form>
      <template #footer>
        <n-space>
          <n-button type="primary" @click="onFinish">提交</n-button>
          <n-button @click="show = false">取消</n-button>
        </n-space>
      </template>
    </n-drawer-content>
  </n-drawer>
</template>

<style scoped>

</style>